<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\api\controller;
use think\Db;
class Myinfo extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');
        extract(input());
        if($user_id != 0){
            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
            if($auth == 112){
                echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
                exit;
            }elseif($auth == 110){
                echo json_encode(['status' => 302, 'msg' => $this->frost]);
                exit;
            }elseif($auth == 1103){
                echo json_encode(['status' => 303, 'msg' => $this->del]);
                exit;
            }
        }

    }


    /**
     * 我的地址
     */
    public function myAddress()
    {
        extract(input());
        $field = 'u.*';
        $field .= ',a.district sheng,aa.district shi,aaa.district qu';
        $address = Db::table('up_my_address')->alias('u')
            ->join('up_area a','u.address_sheng=a.district_id','LEFT')
            ->join('up_area aa','u.address_shi=aa.district_id','LEFT')
            ->join('up_area aaa','u.address_qu=aaa.district_id','LEFT')
            ->where('address_user_id',$user_id)
            ->where('address_del',1)
            ->order('address_default DESC')
            ->field($field)
            ->page($page,10)
            ->select();
        return json(['status'=>200,'msg'=>$address]);
    }
    /**
     * 我的地址——添加
     */
    public function myAddressAdd()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        if(empty($address_name) || empty($address_phone)){
            return json(['status'=>1,'msg'=>'名字和联系电话不能为空']);
        }
        $address_detail = trim($address_detail);
        if(!$sheng || !$shi || !$qu || !$address_detail){
            return json(['status'=>1,'msg'=>'地址不能为空']);
        }
        if($sheng == '1231231231'){
            return json(['status'=>1,'msg'=>'请选择正确的地址']);
        }
        if(mb_strlen($address_name) >= 11) return json(['status'=>1,'msg'=>'收件人不能超过10个汉字']);
        if(mb_strlen($address_detail) >= 41) return json(['status'=>1,'msg'=>'详细地址不能超过40个汉字']);
        if(mb_strlen($address_detail) < 4) return json(['status'=>1,'msg'=>'详细地址不能少于4个汉字']);
        $address = [
            'address_name' => $address_name,
            'address_phone' => $address_phone,
            'address_sheng' => $sheng,
            'address_shi' => $shi,
            'address_qu' => $qu,
            'address_detail' => $address_detail,
            'address_time' => $today,
            'address_update_time' => $today,
            'address_default' => $address_default,
            'address_user_id' => $user_id,
            'address_uson_id' => 0,
        ];
        if($address_default == 2){
            Db::table('up_my_address')
                ->where('address_user_id',$user_id)
                ->where('address_del',1)
                ->setField('address_default',1);
        }
        $res = Db::table('up_my_address')->insertGetId($address);
        if($res){
            return json(['status'=>200,'msg'=>'操作成功','address_id' => $res]);
        }else{
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }
    /**
     * 我的地址——编辑（待定）
     */
    public function myAddressEdit()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        if(empty($address_name) || empty($address_phone)){
            return json(['status'=>1,'msg'=>'名字和联系电话不能为空']);
        }
        $address_detail = trim($address_detail);
        if(!$sheng || !$shi || !$qu || !$address_detail){
            return json(['status'=>1,'msg'=>'地址不能为空']);
        }
        if($sheng == '1231231231'){
            return json(['status'=>1,'msg'=>'请选择正确的地址']);
        }
        if(mb_strlen($address_name) >= 11) return json(['status'=>1,'msg'=>'收件人不能超过10个汉字']);
        if(mb_strlen($address_detail) >= 41) return json(['status'=>1,'msg'=>'详细地址不能超过40个汉字']);
        if(mb_strlen($address_detail) < 4) return json(['status'=>1,'msg'=>'详细地址不能少于4个汉字']);
        $address = [
            'address_name' => $address_name,
            'address_phone' => $address_phone,
            'address_sheng' => $sheng,
            'address_shi' => $shi,
            'address_qu' => $qu,
            'address_detail' => $address_detail,
            'address_time' => $today,
            'address_update_time' => $today,
            'address_default' => $address_default,
            'address_user_id' => $user_id,
            'address_uson_id' => 0,
        ];
        if($address_default == 2){
            Db::table('up_my_address')
                ->where('address_user_id',$user_id)
                ->where('address_del',1)
                ->setField('address_default',1);
        }
        $res = Db::table('up_my_address')->where('address_id',$address_id)->update($address);
        if($res){
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }

    /**
     * 获取某个地址的详情
     * @return \think\response\Json
     */
    public function getOneAddress()
    {
        extract(input());
        $address = $this->myAddressInfo($user_id,$address_id);
        if(empty($address)){
            $address = '';
        }
        return json(['status'=>200,'address'=>$address]);
    }
    /**
     * 删除某个地址
     * @return \think\response\Json
     */
    public function delAddress()
    {
        extract(input());
        $res = Db::table('up_my_address')->where('address_id',$address_id)->setField('address_del',2);
        if($res){
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }
    /**
     * 把某个地址设为默认
     * @return \think\response\Json
     */
    public function setDefaultAddress()
    {
        extract(input());
        Db::table('up_my_address')
            ->where('address_user_id',$user_id)
            ->where('address_del',1)
            ->setField('address_default',1);
        $res = Db::table('up_my_address')->where('address_id',$address_id)->setField('address_default',2);
        if($res){
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }
    /**
     * 我收藏的商品
     * @return \think\response\Json
     */
    public function myLikeGoods()
    {
        extract(input());
        //先都弄正常
        Db::table('up_like_goods')
            ->where('l_user_id',$user_id)
            ->setField('l_good_status',1);
        //把自营的非上架的改掉
        Db::table('up_like_goods')->alias('g')
            ->join('up_self_goods s','g.l_good_id=s.good_id','LEFT')
            ->where('l_user_id',$user_id)
            ->where('l_type',1)
            ->where('good_status','<>',1)
            ->setField('l_good_status',2);
        //把增补的非上架的改掉
        Db::table('up_like_goods')->alias('g')
            ->join('up_goods s','g.l_good_id=s.good_id','LEFT')
            ->where('l_user_id',$user_id)
            ->where('l_type',2)
            ->where('good_status','<>',1)
            ->setField('l_good_status',2);


        $gids = Db::table('up_like_goods')
            ->where('l_user_id',$user_id)
            ->where('l_good_status',1)
            ->order('l_time DESC')
            ->page($page,12)
            ->field('l_type,l_good_id')
            ->select();
        $data = [];
        if($gids){
            foreach ($gids as $k=>$v){
                $table = 'up_goods';
                if($v['l_type'] == 1){
                    $table = 'up_self_goods';
                }
                $field = 'good_id,good_name,good_price,good_thumb,school_name,school_id';
                $now = Db::table($table)->alias('g')
                    ->join('up_school s','g.good_school=s.school_id','LEFT')
                    ->where('good_id',$v['l_good_id'])
                    ->field($field)
                    ->find();
                $now['l_type'] = $v['l_type'];
                $data[$k] = $now;
            }
        }
//        $gids = Db::table('up_like_goods')
//            ->where('l_user_id',$user_id)
//            ->where('l_type',1)
//            ->order('l_time DESC')
//            ->page($page,12)
//            ->column('l_good_id');
//        $where = [
//            'good_status' => 1,
//            'good_id' => ['in',$gids]
//        ];
//        $field = 'good_id,good_name,good_price,good_thumb,school_name,school_id';
//        $data = Db::table('up_self_goods')->alias('g')
//            ->join('up_school s','g.good_school=s.school_id','LEFT')
//            ->where($where)
////            ->where('good_stock','>',0)
//            ->field($field)
//            ->order('good_create_time DESC')
//            ->page ($page,10)
//            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }

//    --------------------------消息通知----------------------------------------------------
    /**
     * 有没有未读消息
     */
    public function haveNoticeRed()
    {
        extract(input());
        $time = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->value('user_time');
        $data = Db::table('up_notice')
            ->where(function ($query) use ($time,$user_id) {
                $query->where('n_type', 1)->where('n_range', 1)->where('n_send_datetime', '>=', $time)->where('n_del_user_id','not like',"%,$user_id,%")->where('n_read_user_id','not like',"%,$user_id,%");
            })
            ->whereOr(function ($query) use ($user_id) {
                $query->where('n_type', 1)->where('n_range', '>',1)->where('n_user_id', 'like',"%,$user_id,%")->where('n_del_user_id','not like',"%,$user_id,%")->where('n_read_user_id','not like',"%,$user_id,%");
            })
            ->whereOr(function ($query) use ($user_id) {
                $query->where('n_type', '>',1)->where('n_user_id', $user_id)->where('n_read_user_id',0);
            })
            ->find();
        $have = 0;
        if($data){
            $have = 1;
        }
        return json(['status'=>200,'msg'=>$have]);
    }
    /**
     * 获取所有和我有关的消息
     * type：1是系统消息 2是喜欢 3是共同喜欢 4是动态点赞 5是评论点赞 6是评论
     * @return string
     */
    public function getNotice(){
        extract(input());
        if($type == 1) {
            $time = Db::table('up_u_user')
                ->where('user_id', $user_id)
                ->value('user_time');
            $data = Db::table('up_notice')
                ->where(function ($query) use ($time,$user_id) {
                    $query->where('n_type', 1)->where('n_range', 1)->where('n_send_datetime', '>=', $time)->where('n_del_user_id','not like',"%,$user_id,%");
                })
                ->whereOr(function ($query) use ($user_id) {
                    $query->where('n_type', 1)->where('n_range', '>',1)->where('n_user_id', 'like',"%,$user_id,%")->where('n_del_user_id','not like',"%,$user_id,%");
                })
                ->field('n_title,n_content,n_read_user_id,n_id,n_range,n_send_datetime,n_type')
                ->order('n_send_datetime DESC')
                ->page($page, 20)
                ->select();
            if($data){
                foreach ($data as $k=>$v){
                    if(!strstr($v['n_read_user_id'],",$user_id,")){
                        $data[$k]['n_read_user_id'] = 0;
                    }else{
                        $data[$k]['n_read_user_id'] = 1;
                    }
                }
            }
        }else{
            $field = 'n_title,user_id,user_username,user_image';
            $field .= ',n_type,n_send_datetime,n_content,n_who,n_app_id,n_id,n_read_user_id';
            $data = Db::table('up_notice')->alias('n')
                ->join('up_u_user u', 'n.n_user_id=u.user_id', 'LEFT')
                ->where('n_user_id', $user_id)
                ->field($field)
                ->order('n_send_datetime DESC')
                ->page($page, 20)
                ->select();
        }
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 消息详情
     */
    public function getNoticeInfo(){
        extract(input());
        $notice = Db::table('up_notice')
            ->where('n_id',$n_id)
            ->find();
        if($notice['n_type'] == 1){
            if(!strstr($notice['n_read_user_id'],",$user_id,")){
                $uids = $notice['n_read_user_id'] . $user_id . ',';
                Db::table('up_notice')
                    ->where('n_id', $n_id)
                    ->setField('n_read_user_id',$uids);
            }
        }else{
            if($notice['n_read_user_id'] == 0){
                Db::table('up_notice')
                    ->where('n_id',$n_id)
                    ->setField('n_read_user_id',1);
            }
        }
        return json(['status'=>200,'msg'=>$notice]);
    }
    /**
     * 删除消息（清空）
     * type：1是系统消息 2是互动消息
     * @return string
     */
    public function delNoticeAll(){
        extract(input());
        if($type == 1) {
            $time = Db::table('up_u_user')
                ->where('user_id', $user_id)
                ->value('user_time');
            $data = Db::table('up_notice')
                ->where(function ($query) use ($time,$user_id) {
                    $query->where('n_type', 1)->where('n_range', 1)->where('n_send_datetime', '>=', $time)->where('n_del_user_id','not like',"%,$user_id,%");
                })
                ->whereOr(function ($query) use ($user_id) {
                    $query->where('n_type', 1)->where('n_range', '>',1)->where('n_user_id', 'like',"%,$user_id,%")->where('n_del_user_id','not like',"%,$user_id,%");
                })
                ->field('n_del_user_id,n_id')
                ->select();
            if($data){
                foreach ($data as $k=>$v){
                    $uids = $v['n_del_user_id'] . $user_id . ',';
                    Db::table('up_notice')
                        ->where('n_id', $v['n_id'])
                        ->setField('n_del_user_id',$uids);
                }
            }
        }else{
            Db::table('up_notice')
                ->where('n_user_id', $user_id)
                ->delete();
        }
        return json(['status'=>200,'msg'=>'操作成功']);
    }
    /**
     * 删除消息：单个删除（待用）
     * @return string
     */
    public function deleteNoticeByIds()
    {
        extract(input());
        $n_id = trim($n_id,',');
        $notice = Db::table('up_notice')
            ->where('n_id','in',$n_id)
            ->field('n_type,n_range,n_del_user_id,n_id')
            ->select();
        foreach ($notice as $k=>$v){
            if($v['n_type'] == 1){
                $uids = $v['n_del_user_id'] . $user_id . ',';
                $res = Db::table('up_notice')
                    ->where('n_id', $v['n_id'])
                    ->setField('n_del_user_id',$uids);
            }else{
                $res = Db::table('up_notice')
                    ->where('n_id',$v['n_id'])
                    ->delete();
            }
        }
        if($res){
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败']);
        }
    }

}